<template>
  <div></div>
</template>

<script>
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/wav'

export default {
  props: {
    sampleBits: {
      type: Number,
      default: 16
    },
    sampleRate: {
      type: Number,
      default: 16000
    },
    format: {
      type: String,
      default: 'wav'
    }
  },
  data() {
    return {
      timer: null,
      recorder: null
    }
  },
  created() {
    this.init()
  },
  mounted() {},
  destroyed() {
    this.stop()
  },
  methods: {
    init() {
      const { sampleBits, sampleRate, format } = this

      this.recorder = Recorder({
        type: format,
        sampleRate,
        bitRate: sampleBits
      })
    },
    open(callback = () => {}) {
      if (!this.recorder) {
        callback(false)
        return
      }

      this.recorder.open(
        () => {
          callback(true)
        },
        (msg, isUserNotAllow) => {
          console.log((isUserNotAllow ? 'UserNotAllow，' : '') + '无法录音:' + msg)
          callback(false)
        }
      )
    },
    start() {
      this.open((success) => {
        if (!success) return

        this.timer = setTimeout(() => {
          this.recorder.start()
        }, 100)
      })
    },
    pause() {
      if (!this.recorder) return

      if (this.getStatus() != 'isRecording') return

      this.recorder.pause()
    },
    resume() {
      if (!this.recorder) return

      if (this.getStatus() != 'isPause') return

      this.recorder.resume()
    },
    async stop(callback = () => {}) {
      if (!this.recorder) return

      const { format } = this
      this.recorder.stop(
        (blob, duration) => {
          const file = new File([blob], `${Date.now()}.${format}`, {
            type: format,
            lastModified: Date.now()
          })
          this.recorder.close()
          callback({
            data: blob,
            file,
            format,
            duration
          })
        },
        (msg) => {
          console.log('录音失败:' + msg)
          this.recorder.close()
        }
      )
    },
    getStatus() {
      if (!this.recorder) return 'isStop'

      const { state } = this.recorder

      if (state === 1) {
        return 'isRecording'
      } else if (state === 2) {
        return 'isPause'
      } else {
        return 'isStop'
      }
    }
  }
}
</script>
<style></style>
